package com.mobzilla.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.mobzilla.model.UserAccount;
import com.mobzilla.service.ServiceFactory;
import com.mobzilla.util.Base64;
import com.mobzilla.util.Constants;

public class LoginActivity extends Activity implements OnClickListener
{
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login);
		
		initListeners();
	}
	
	private void initListeners()
	{
		Button loginButton = (Button)findViewById(R.id.loginButton);
		
		loginButton.setOnClickListener(this);
	}
	
	public void onClick(View v)
	{
		TextView userNameTextField = (TextView)findViewById(R.id.userNameTextField);
		
		String username = userNameTextField.getText().toString();
		
		TextView passwordTextField = (TextView)findViewById(R.id.passwordTextField);
		
		String password = passwordTextField.getText().toString();
		
		String encoded =  Base64.encode(password.getBytes());
		
		if(username == null || username.length() == 0 || password == null || password.length() == 0)
		{
			Toast.makeText(this, "Invalid input.", Toast.LENGTH_LONG).show();
			return;
		}
		
		if(ServiceFactory.getLoginServiceInstance().authenticateUser(username, password))
		{
			UserAccount u = new UserAccount(username, password);
			
			Constants.setUserAccount(u);
			
			Intent i = new Intent(this, MainMenuActivity.class);
			startActivity(i);
		}
		else
		{
			Toast.makeText(this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
		}		
	}
}
